import java.util.Random;
import java.util.concurrent.TimeUnit;

public class ProducerConsumerTest {

	public static void main(String[] args) throws InterruptedException {
		ProducerConsumerPool pool = new ProducerConsumerPool();
		ProducerConsumerPool.Producer p1 = pool.new Producer();
		ProducerConsumerPool.Consumer c1 = pool.new Consumer();
		Thread t1 = new Thread(p1);
		Thread t2 = new Thread(c1);
		t1.start();
		t2.start();
		t1.join();
		t2.join();
		System.out.println("Now the count of poo is "+pool.getCount());
	}
}

class ProducerConsumerPool{
	private static final int ITEMS = 1000;
	private int count = 0;
	public synchronized int  getCount(){
		return count;
	}
	public synchronized void  setCount(int i){
		count = i;
	}
	public  synchronized void produce(){  //加synchronized同步
		/*while(getCount()>=ITEMS){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}*/
		setCount(getCount()+1);
		notify();
	}
	public synchronized void consume(){   //加synchronized同步
		while(getCount()==0){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		setCount(getCount()-1);
		notify();
	}
	
	public class Producer implements Runnable {
		public void run() {
			try{
				for (int i = 0; i < ITEMS; i++){
					produce();
					TimeUnit.NANOSECONDS.sleep(new Random().nextInt(5));
				}
			}catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+" produed "+ITEMS+ " now the count is "+count);
		}
	}

	public class Consumer implements Runnable {
		public void run() {
			try {
				for (int i = 0; i < ITEMS; i++){
					consume();
					TimeUnit.NANOSECONDS.sleep(new Random().nextInt(5));
				}
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+" consumed "+ITEMS+ " now the count is "+count);
		}
	}
}
